<template>
  <div class="a-header">
    <span class="title-name return-left" @click="toReturn(1)">
      <img src="../../assets/img/popup_icon_tuihui_defa.png" alt="" />返回
    </span>
    <!-- <a-breadcrumb>
      <a-breadcrumb-item class="title-name" @click="toReturn(1)">公文流转 / </a-breadcrumb-item>
      <a-breadcrumb-item class="title-name" @click="toReturn(2)">收文登记 / </a-breadcrumb-item>
      <a-breadcrumb-item class="now-name">{{ documentTitle }}</a-breadcrumb-item>
    </a-breadcrumb> -->
  </div>
  <div class="a-main">
    <div class="main-left">
      <div class="main-left-cont">
        <a-tabs v-model:activeKey="activeKey" @change="tabsChange">
          <a-tab-pane key="1" tab="详情">
            <div class="a-cont">
              <MyForm
                ref="fromItem"
                :form-fields="formFields"
                :get-info="getInfo"
                :line-data="lineData"
                @returnBtns="returnBtns"
                @changeRadio="changeRadio"
              ></MyForm>
            </div>
          </a-tab-pane>
          <a-tab-pane v-if="editSeparately * 1 === 1" key="2" tab="正文" force-render>
            <div class="a-right-cont" :class="!flag ? 'no-right' : nill">
              <div v-if="!flag" class="a-upload-button" @click="toEditor()">
                <svg-icon icon-class="btn_edit" class-name="icon-select-date"></svg-icon>
                切换在线编辑
              </div>
              <a-upload
                v-model:file-list="fileList"
                list-type="picture"
                accept=".doc, .docx, .wps, .ofd, .pdf, .jpeg, .jpg, .png"
                :multiple="true"
                :custom-request="customRequest"
              >
                <div v-if="flag" class="a-upload-button">
                  <!-- <img src="@/assets/img/icon_upload_shangchuanwenjian@2x.png" alt="" /> -->
                  <svg-icon
                    icon-class="icon_upload_shangchuanwenjian"
                    class-name="icon-select-date"
                  ></svg-icon>
                  直接上传正文
                </div>
              </a-upload>
              <!-- 富文本 -->
              <BasicEditor
                v-if="activeKey * 1 === 2 && flag"
                :catch-data="catchData"
                :catchpure-data="catchPureData"
                :content="wangEditorData"
                :style="'big'"
              ></BasicEditor>
              <div v-if="!flag" class="i-from">
                <iframe
                  :src="preview"
                  style="height: 1004px"
                  width="100%"
                  loading="lazy"
                  frameborder="0"
                  class="iframes"
                ></iframe>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <div class="main-right">
      <div class="main-right-top">
        <div class="fubox-title">审批流程</div>
        <div class="content-sectio">
          <div class="cont-step">
            <div class="steps">
              <div v-for="(item, index) in state.getLineData" :key="item.id" class="steps-items">
                <div v-if="isShow(item)" class="steps-item">
                  <div class="steps-item-left">
                    <i class="Icon"></i>
                    <div class="lines"></div>
                  </div>
                  <div class="steps-item-right">
                    <FlowItem
                      v-if="item.nodeType !== '3'"
                      :title="item.nodeName"
                      :node-id="item.nodeId"
                      :people-is-multiple="item.optionalType === '2'"
                      :is-people="item.checkScope === '2'"
                      :people="item.oaNodeUserDtoS"
                      :select-people="item.selectPeople"
                      :index="index"
                      :check-type="item.checkType"
                      :fixed="
                        item.checkType === '1' ||
                        item.checkType === '4' ||
                        item.checkType === '6' ||
                        item.checkType === '7'
                      "
                      :symbol="item.symbol"
                      v-on:toResult="getAryByOaFlowApply"
                      @toReturnPeople="toReturnPeople"
                    >
                    </FlowItem>
                    <CopyItem
                      v-else-if="
                        (item.nodeType == 3 && item.addCopyUserId != 0) ||
                        item.oaNodeUserDtoS.length !== 0
                      "
                      :title="item.nodeName"
                      :node-id="item.nodeId"
                      :check-type="item.checkType"
                      :people-is-multiple="true"
                      :is-people="item.checkScope === '2'"
                      :people="item.oaNodeUserDtoS"
                      :select-people="item.selectPeople"
                      :is-user-add="item.addCopyUserId === '1'"
                      :symbol="item.symbol"
                      v-on:toResult="getAryByOaFlowCc"
                    >
                    </CopyItem>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="main-right-bottom">
        <!-- 按钮 -->
        <div class="bottom-button">
          <a-button class="urging" type="primary" @click="onSubmit">提交</a-button>
        </div>
      </div>
      <!-- <FlowPathComponent></FlowPathComponent> -->
    </div>
  </div>

  <!-- 返回弹窗 -->
  <a-modal
    v-model:visible="returnVisible"
    class="return-box"
    width="340px"
    :closable="false"
    :footer="null"
  >
    <div class="model-head">
      <div class="head-left">
        <img src="../../assets/img/xiangqing_icon_tixing@2x.png" alt="" />
        <div>提示</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="cancel" />
    </div>
    <div class="model-body"> {{ title }} </div>
    <div class="btn-list">
      <a-button @click="cancel">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
// import { UploadOutlined } from '@ant-design/icons-vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import BasicEditor from '../../components/wangEditor/index.vue';
import MyModal from '../../components/formPageDialog';
import MyForm from '../../components/formComponent/index.vue';
// import DiaLog from '../../components/settingDialog/index.vue';
import FlowItem from '@/components/flowItem/flowItem.vue';
import { getAccessGet } from '@/api/receiveDetails';
import CopyItem from '@/components/copyItem/copyItem.vue';
import { Interface } from '@/api/official/official.js';
import ObsClient from 'esdk-obs-browserjs';
import moment from 'moment';
const route = useRoute();
const router = useRouter();
const visible = ref(false);
const documentTitle = ref(route.query.templateName); //  标题
let returnVisible = ref(false); // 返回提示窗状态
function cancel() {
  returnVisible.value = false;
}
function handleOk() {
  if (edit.value === 'routeReturn') {
    sessionStorage.setItem('tabsActive', '公文收发');
    router.push({
      path: '/index'
    });
  } else {
    if (flag.value) {
      getFile(uploadFile.value);
    } else {
      fileList.value = [];
      preview.value = '';
      fromItem.value.getFileUrl(flag.value, null);
    }
    flag.value = !flag.value;
  }

  returnVisible.value = false;
}
let activeKey = ref('1');
function tabsChange(val) {
  activeKey.value = val;
  wangEditorData.value = html.value;
}
let dataChangeShow = ref(false); // 页面数据是否变化
function returnBtns(val) {
  dataChangeShow.value = val;
}
function changeRadio(val) {
  getFlow(val);
}
let title = ref(''); // 弹唱提示
// 面包屑返回
function toReturn(val) {
  edit.value = 'routeReturn';
  if (!dataChangeShow.value) {
    sessionStorage.setItem('startingActive', '0');
    sessionStorage.setItem('tabsActive', '公文收发');
    router.push({
      path: '/index'
    });
  } else {
    title.value = '离开当前页面数据会丢失，确定吗？';
    returnVisible.value = true;
  }
}
const flag = ref(true);
const fileList = ref([]); // 正文数据
const formFields = ref([]);
const lineData = ref([]);
const state = reactive({
  initiateData: [], // 发起人数组
  getdata: [], // 动态表单数组
  assigneeList: {}, // 提交流程人员
  assigneeListClone: {}, // 提交流程人员信息
  getLineData: [], // 获取流程
  isFormListPage: true, // 从formList和表单详情过来的，从消息过来的时false，消息过来的【安卓和苹果和PC】不展示返回按钮
  formId: '',
  formName: '',
  reason: '',
  processId: '',
  flowApplyStr: '',
  flowCcStr: '',
  getNodeData: [], // 提交的节点数据
  getNodeDataObj: {},
  submitForm: [],
  linesShow: false, // 控制发起及结束的判断
  totalMessage: '', // '流程将会在必填信息填写后自动显示。',
  longTime: true // 判断时长是否为空
});
let getInfo = ref(''); // 接口获取所有数据
let editSeparately = ref(''); // 正文tab状态
let iValue = ref(30237);
onMounted(() => {
  if (process.env.VUE_APP_WEB_URLS === 'dev' || process.env.VUE_APP_WEB_URLS === 'test') {
    bucket.value = 'tj-saas-test';
    iValue.value = 30237;
  }
  if (process.env.VUE_APP_WEB_URLS === 'preview') {
    bucket.value = 'saas-pre';
    iValue.value = 32109;
  }
  if (process.env.VUE_APP_WEB_URLS === 'pro') {
    bucket.value = 'resource-pool-obs';
    iValue.value = 29781;
  }
  getInit();
});
let deptId = ref(''); // 组织id
function getInit() {
  // 模板详情
  Interface.GetFormInfo(route.query.id).then(res => {
    let bumenOptions = [];
    if (res.data.isDeptCheckType * 1 === 1 && res.data.deptInfos.length > 1) {
      res.data.deptInfos.forEach(item => {
        bumenOptions.push({ value: item.deptName, key: item.deptBusinessId });
      });
      deptId.value = res.data.deptInfos[0].deptBusinessId;
    } else {
      deptId.value = res.data.deptInfos[0].deptBusinessId;
    }
    res.data.controls.forEach(it => {
      it.props.content = '';
      if (it.componentName === 'DDMultiSelectField') it.props.contents = [];
      if (
        it.componentName === 'UrgencyLevelSelect' ||
        it.componentName === 'DDSelectField' ||
        it.componentName === 'SecretLevelSelect'
      ) {
        it.props.contents = null;
      }
      if (
        it.componentName === 'DDDateField' ||
        it.componentName === 'ReceivedOnDate' ||
        it.componentName === 'SendOnDate'
      ) {
        it.props.contents = '';
      }
    });
    editSeparately.value = res.data.editSeparately;
    getInfo.value = res.data;
    let zuzhi = [
      {
        componentName: 'bumen',
        props: {
          componentName: 'bumen',
          required: '1',
          content: deptId.value,
          option: bumenOptions,
          label: '部门'
        }
      }
    ];
    let fileLists = res.data.controls.filter(item => item.componentName !== 'Initiator');
    formFields.value = bumenOptions.length > 1 ? [...zuzhi, ...fileLists] : fileLists;
    // 流程信息
    getFlow(deptId.value);
  });
}
function getFlow(deptIds) {
  let prams = {
    formId: route.query.id,
    deptId: deptIds, // 组织id
    contents: [
      {
        cmpId: route.query.procDefId,
        content: ''
      }
    ]
  };
  Interface.GetLineInfo(prams).then(res => {
    let userInfo = JSON.parse(sessionStorage.getItem('USER_INFO'));
    let list = [
      {
        nodeName: '创建人',
        id: '16899870182371269',
        nodeId: 'sid__EA0b30PlhgGfvplocMhu',
        formId: '1682553619360358401',
        selfMultiExamineType: '1',
        nodeType: '4',
        parentId: 'sid_VYRfjt_Lr0sHNzgtNReS4',
        deptIds: '',
        schoolIds: '',
        addCopyUserId: '1',
        copyAdmin: '1',
        copyDirector: '1',
        checkType: '1',
        optionalType: '2',
        checkScope: '1',
        examineEnd: '1',
        continueExistsType: '2',
        deptManageType: '1',
        examineType: '1',
        examineExistsType: '2',
        directDeptManageType: '1',
        oaNodeUserDtoS: [
          {
            id: userInfo.businessId,
            avatar: userInfo.avatar,
            username: userInfo.username,
            userId: userInfo.businessId
          }
        ]
      }
    ];
    // lineData.value = res.data;
    // lineData.value = [...list, ...res.data];
    lineData.value = res.data;
    GetLine();
  });
}
let edit = ref(''); //  正文切换
const toEditor = () => {
  title.value = '当前已编辑正文，切换上传模式会造成数据丢失，确定操作吗？';
  edit.value = 'zhngwenEdit';
  returnVisible.value = true;
};
let uploadFile = ref(); // 上传数据
// 上传附件
function customRequest(file) {
  if (html.value) {
    uploadFile.value = file;
    title.value = '当前已编辑正文，切换上传模式会造成数据丢失，确定操作吗？';
    edit.value = 'zhngwenEdit';
    returnVisible.value = true;
  } else {
    console.log(file);
    getFile(file);
  }
}
function getFile(file) {
  let fileName = file.file.name;
  let name = fileName.substring(0, fileName.lastIndexOf('.'));
  let fileType = fileName.substr(-4);
  console.log(fileType, '???');
  if (
    file.file.type !== 'application/pdf' &&
    file.file.type !== 'image/png' &&
    file.file.type !== 'image/jpeg' &&
    file.file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' &&
    file.file.type !== 'application/msword' &&
    file.file.type !== 'application/kswps' &&
    fileType !== '.ofd' &&
    fileType !== '.OFD'
  ) {
    file.file['status'] = 'error';
    file.file['response'] = '请上传doc、docx、wps、ofd、pdf、png、jpg、jpeg文件';
    message.error('请上传doc、docx、pdf、png、jpg、jpeg文件');
    file.pop();
    return;
  } else if (name.length > 50) {
    file.file['status'] = 'error';
    file.file['response'] = '图像名超出字符限制，请修改后重新上传!';
    message.error('图像名超出字符限制，请修改后重新上传!');
    file.pop();
    return;
  } else {
    file.file['status'] = 'done';
    file.file['time'] = moment().format('YYYY-MM-DD');
    file.file['math'] = Math.random();
    file.file['nameUrl'] = file.file.math + '/' + file.file.name.replace(/\s+/g, '');
    file.file['urlTime'] = 'documentCirculation/' + file.file.time + '/' + file.file.nameUrl;
    uploadOBS(file.file);
  }
}
let annexList = ref([]); // 上传成功附件
const preview = ref(); // 预览前缀
let bucket = ref('tj-saas-test'); // 桶名
function uploadOBS(file) {
  let fileDir = file.urlTime;
  let SourceFile = file;
  let id;
  let key;
  getAccessGet().then(res => {
    id = res.data.Accesskeyid;
    key = res.data.Signature;
  });
  // id = 'TODD7COQ9OY55YNUYHEC';
  // key = 'DmX1sTbrl0OGRnPKDTlXvup6DP2S9Txe4hKy6eRO';
  let obsClient = new ObsClient({
    // access_key_id: id,
    // secret_access_key: key,
    access_key_id: 'TODD7COQ9OY55YNUYHEC',
    secret_access_key: 'DmX1sTbrl0OGRnPKDTlXvup6DP2S9Txe4hKy6eRO',
    server: 'https://obs.cn-east-3.myhuaweicloud.com'
  });
  obsClient.putObject(
    {
      Bucket: bucket.value,
      Key: fileDir,
      SourceFile: SourceFile // 文件encodeURIComponent
    },
    function (err, result) {
      if (err) {
        message.error('上传失败');
      } else {
        let list = [];
        message.success('上传成功');
        fileList.value.forEach(item => {
          if (item.originFileObj.status === 'done') {
            list.push({
              url:
                `https://${bucket.value}.obs.cn-east-3.myhuaweicloud.com/documentCirculation/` +
                item.originFileObj.time +
                '/' +
                getFileUrls(item),
              name: item.originFileObj.name,
              nameUrl: item.originFileObj.nameUrl,
              previewType: item.originFileObj.previewType
            });
          }
          flag.value = false;
          annexList.value = list;
          preview.value = `https://ow365.cn/?i=${iValue.value}&ssl=1&pct=1&furl=` + list[0].url;
          console.log(preview.value, '????');
          fromItem.value.getFileUrl(flag.value, list[0].url); // 正文url
        });
      }
    }
  );
}
function getFileUrls(file) {
  let types = file.originFileObj.name
    .replace(/\s+/g, '')
    .substring(file.originFileObj.name.replace(/\s+/g, '').lastIndexOf('.'));
  let three = file.originFileObj.name.substring(0, file.originFileObj.name.lastIndexOf('.'));
  return file.name.indexOf('%') !== -1
    ? file.originFileObj.math + '/' + encodeURIComponent(three) + types
    : file.originFileObj.nameUrl;
}
let fromItem = ref(''); // 表单子组件
const onSubmit = () => {
  fromItem.value.handleSubmit(); // 执行表单组件提交方法
};
const GetLine = () => {
  let arr = lineData.value.map(item => {
    let symbol = '+';
    if (
      (item.nodeType === '2' &&
        (item.checkType === '1' || item.checkType === '4' || item.checkType === '6')) ||
      (item.nodeType === '4' &&
        (item.checkType === '1' || item.checkType === '4' || item.checkType === '6'))
    ) {
      if (item.selfMultiExamineType === '1') {
        symbol = '+';
      } else if (item.selfMultiExamineType === '2') {
        symbol = '+';
      } else if (item.selfMultiExamineType === '3') {
        symbol = '+';
      }
    } else if (
      (item.nodeType === '2' &&
        (item.checkType === '2' || item.checkType === '4' || item.checkType === '6')) ||
      (item.nodeType === '4' &&
        (item.checkType === '2' || item.checkType === '4' || item.checkType === '6'))
    ) {
      if (item.multiExamineType === '1') {
        symbol = '+';
      } else if (item.multiExamineType === '2') {
        symbol = '+';
      } else if (item.multiExamineType === '3') {
        symbol = '+';
      }
    }
    if (item.nodeType === '3' || item.checkType === '1') {
      state.assigneeList[`${item.nodeId}`] = item.oaNodeUserDtoS.map(item => {
        return item.id === undefined ? item.userId : item.id;
      });
    }

    return {
      ...item,
      symbol: symbol
    };
  });
  arr.forEach(item => {
    if (item.checkType * 1 === 2) {
      // 只有发起人自选的时候把后台给的反显人 oaNodeUserDtoS， 赋值给 selectPeople, 用于展示可以选择的人.(把selectPeople当作可以选择分人的list;oaNodeUserDtoS是最终选中人的list )
      item.selectPeople = item.oaNodeUserDtoS;
    }
  });
  state.getLineData = arr;
};
// 流程是否展示
const isShow = item => {
  if (item.addCopyUserId !== 0 || item.oaNodeUserDTOS.length !== 0) {
    return true;
  } else {
    return false;
  }
};
const textData = ref('');
const wangEditorData = ref(''); // 富文本内容
const html = ref(''); // 富文本html
// 富文本内容带标签
function catchData(e) {
  if (e === '<p><br/></p>') {
    html.value = '';
  } else {
    html.value = e;
  }
  fromItem.value.getFileUrl(flag.value, html.value); // 正文url
}
// 富文本内容
function catchPureData(e) {
  textData.value = e;
}
// 获得选人组件人
function toReturnPeople(val, index) {
  state.getLineData[index].oaNodeUserDtoS = val;
  lineData.value[index].oaNodeUserDtoS = val;
  fromItem.value.allData(state.getLineData);
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>
